import React, { useState } from 'react'
import {
  Card,
  Button,
  Space,
  Modal,
  Form,
  Select,
  DatePicker,
  InputNumber,
  Switch,
  Typography,
  Alert,
  Progress,
  Descriptions,
  message,
  Popconfirm,
} from 'antd'
import {
  DeleteOutlined,
  DownloadOutlined,
  SettingOutlined,
  CleaningServicesOutlined,
  WarningOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons'
import { formatFileSize, formatDateTime } from '@/utils'

const { RangePicker } = DatePicker
const { Option } = Select
const { Text, Title } = Typography

interface LogCleanupConfig {
  retentionDays: number
  maxLogSize: number // MB
  autoCleanup: boolean
  cleanupSchedule: 'daily' | 'weekly' | 'monthly'
  keepErrorLogs: boolean
}

interface LogExportConfig {
  format: 'json' | 'csv' | 'txt'
  dateRange?: [string, string]
  levels?: string[]
  connections?: string[]
  includeMetadata: boolean
  maxRecords?: number
}

interface LogStats {
  totalLogs: number
  totalSize: number // bytes
  oldestLog: string
  newestLog: string
  logsByLevel: Record<string, number>
  logsByConnection: Record<string, number>
}

interface LogManagementProps {
  logStats?: LogStats
  onCleanup?: (config: LogCleanupConfig) => Promise<void>
  onExport?: (config: LogExportConfig) => Promise<void>
  onUpdateConfig?: (config: LogCleanupConfig) => Promise<void>
  connections?: Array<{
    id: string
    name: string
  }>
}

const LogManagement: React.FC<LogManagementProps> = ({
  logStats,
  onCleanup,
  onExport,
  onUpdateConfig,
  connections = [],
}) => {
  const [cleanupModalVisible, setCleanupModalVisible] = useState(false)
  const [exportModalVisible, setExportModalVisible] = useState(false)
  const [configModalVisible, setConfigModalVisible] = useState(false)
  const [cleanupForm] = Form.useForm()
  const [exportForm] = Form.useForm()
  const [configForm] = Form.useForm()
  const [cleanupProgress, setCleanupProgress] = useState(0)
  const [exportProgress, setExportProgress] = useState(0)
  const [isProcessing, setIsProcessing] = useState(false)

  // 默认清理配置
  const defaultCleanupConfig: LogCleanupConfig = {
    retentionDays: 30,
    maxLogSize: 1024, // 1GB
    autoCleanup: true,
    cleanupSchedule: 'weekly',
    keepErrorLogs: true,
  }

  // 默认导出配置
  const defaultExportConfig: LogExportConfig = {
    format: 'json',
    levels: ['error', 'warn', 'info'],
    includeMetadata: true,
    maxRecords: 10000,
  }

  // 处理日志清理
  const handleCleanup = async () => {
    try {
      const values = await cleanupForm.validateFields()
      setIsProcessing(true)
      setCleanupProgress(0)

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setCleanupProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return prev
          }
          return prev + 10
        })
      }, 200)

      await onCleanup?.(values)
      
      clearInterval(progressInterval)
      setCleanupProgress(100)
      
      setTimeout(() => {
        setCleanupModalVisible(false)
        setCleanupProgress(0)
        setIsProcessing(false)
        message.success('日志清理完成')
      }, 1000)
    } catch (error) {
      setIsProcessing(false)
      setCleanupProgress(0)
      message.error('日志清理失败')
    }
  }

  // 处理日志导出
  const handleExport = async () => {
    try {
      const values = await exportForm.validateFields()
      setIsProcessing(true)
      setExportProgress(0)

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setExportProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return prev
          }
          return prev + 10
        })
      }, 300)

      await onExport?.(values)
      
      clearInterval(progressInterval)
      setExportProgress(100)
      
      setTimeout(() => {
        setExportModalVisible(false)
        setExportProgress(0)
        setIsProcessing(false)
        message.success('日志导出完成')
      }, 1000)
    } catch (error) {
      setIsProcessing(false)
      setExportProgress(0)
      message.error('日志导出失败')
    }
  }

  // 处理配置更新
  const handleUpdateConfig = async () => {
    try {
      const values = await configForm.validateFields()
      await onUpdateConfig?.(values)
      setConfigModalVisible(false)
      message.success('配置更新成功')
    } catch (error) {
      message.error('配置更新失败')
    }
  }

  return (
    <div>
      {/* 日志统计 */}
      {logStats && (
        <Card title="日志统计" size="small" style={{ marginBottom: 16 }}>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="总日志数">
              {logStats.totalLogs.toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="总大小">
              {formatFileSize(logStats.totalSize)}
            </Descriptions.Item>
            <Descriptions.Item label="最早日志">
              {formatDateTime(logStats.oldestLog)}
            </Descriptions.Item>
            <Descriptions.Item label="最新日志">
              {formatDateTime(logStats.newestLog)}
            </Descriptions.Item>
          </Descriptions>

          {/* 按级别统计 */}
          <div style={{ marginTop: 16 }}>
            <Text strong>按级别统计：</Text>
            <div style={{ marginTop: 8 }}>
              <Space wrap>
                {Object.entries(logStats.logsByLevel).map(([level, count]) => (
                  <div key={level} style={{ 
                    padding: '4px 8px',
                    background: '#f5f5f5',
                    borderRadius: 4,
                    fontSize: 12,
                  }}>
                    <Text strong>{level.toUpperCase()}:</Text> {count}
                  </div>
                ))}
              </Space>
            </div>
          </div>

          {/* 按连接统计 */}
          {Object.keys(logStats.logsByConnection).length > 0 && (
            <div style={{ marginTop: 16 }}>
              <Text strong>按连接统计：</Text>
              <div style={{ marginTop: 8 }}>
                <Space wrap>
                  {Object.entries(logStats.logsByConnection).map(([connection, count]) => (
                    <div key={connection} style={{ 
                      padding: '4px 8px',
                      background: '#f5f5f5',
                      borderRadius: 4,
                      fontSize: 12,
                    }}>
                      <Text strong>{connection}:</Text> {count}
                    </div>
                  ))}
                </Space>
              </div>
            </div>
          )}
        </Card>
      )}

      {/* 操作按钮 */}
      <Card title="日志管理" size="small">
        <Space>
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={() => setExportModalVisible(true)}
          >
            导出日志
          </Button>
          
          <Button
            icon={<DeleteOutlined />}
            onClick={() => setCleanupModalVisible(true)}
          >
            清理日志
          </Button>
          
          <Button
            icon={<SettingOutlined />}
            onClick={() => setConfigModalVisible(true)}
          >
            清理配置
          </Button>
        </Space>
      </Card>

      {/* 日志清理模态框 */}
      <Modal
        title={
          <Space>
            <DeleteOutlined />
            <span>日志清理</span>
          </Space>
        }
        open={cleanupModalVisible}
        onCancel={() => !isProcessing && setCleanupModalVisible(false)}
        footer={[
          <Button 
            key="cancel" 
            onClick={() => setCleanupModalVisible(false)}
            disabled={isProcessing}
          >
            取消
          </Button>,
          <Popconfirm
            key="confirm"
            title="确定要清理日志吗？此操作不可恢复！"
            onConfirm={handleCleanup}
            okText="确定清理"
            cancelText="取消"
            disabled={isProcessing}
          >
            <Button 
              type="primary" 
              danger
              loading={isProcessing}
            >
              开始清理
            </Button>
          </Popconfirm>,
        ]}
        maskClosable={!isProcessing}
      >
        <Alert
          message="警告"
          description="日志清理操作不可恢复，请谨慎操作！建议先导出重要日志。"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />

        {isProcessing ? (
          <div>
            <Text>正在清理日志...</Text>
            <Progress percent={cleanupProgress} style={{ marginTop: 8 }} />
          </div>
        ) : (
          <Form
            form={cleanupForm}
            layout="vertical"
            initialValues={{
              retentionDays: 30,
              keepErrorLogs: true,
            }}
          >
            <Form.Item
              name="retentionDays"
              label="保留天数"
              rules={[{ required: true, message: '请输入保留天数' }]}
            >
              <InputNumber
                min={1}
                max={365}
                style={{ width: '100%' }}
                addonAfter="天"
              />
            </Form.Item>

            <Form.Item
              name="keepErrorLogs"
              label="保留错误日志"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>

            <Form.Item
              name="levels"
              label="清理级别"
            >
              <Select
                mode="multiple"
                placeholder="选择要清理的日志级别"
                allowClear
              >
                <Option value="debug">DEBUG</Option>
                <Option value="info">INFO</Option>
                <Option value="warn">WARN</Option>
                <Option value="error">ERROR</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="connections"
              label="清理连接"
            >
              <Select
                mode="multiple"
                placeholder="选择要清理的连接日志"
                allowClear
              >
                {connections.map(conn => (
                  <Option key={conn.id} value={conn.id}>
                    {conn.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        )}
      </Modal>

      {/* 日志导出模态框 */}
      <Modal
        title={
          <Space>
            <DownloadOutlined />
            <span>导出日志</span>
          </Space>
        }
        open={exportModalVisible}
        onCancel={() => !isProcessing && setExportModalVisible(false)}
        footer={[
          <Button 
            key="cancel" 
            onClick={() => setExportModalVisible(false)}
            disabled={isProcessing}
          >
            取消
          </Button>,
          <Button 
            key="export" 
            type="primary"
            onClick={handleExport}
            loading={isProcessing}
          >
            开始导出
          </Button>,
        ]}
        maskClosable={!isProcessing}
      >
        {isProcessing ? (
          <div>
            <Text>正在导出日志...</Text>
            <Progress percent={exportProgress} style={{ marginTop: 8 }} />
          </div>
        ) : (
          <Form
            form={exportForm}
            layout="vertical"
            initialValues={defaultExportConfig}
          >
            <Form.Item
              name="format"
              label="导出格式"
              rules={[{ required: true, message: '请选择导出格式' }]}
            >
              <Select>
                <Option value="json">JSON</Option>
                <Option value="csv">CSV</Option>
                <Option value="txt">TXT</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="dateRange"
              label="时间范围"
            >
              <RangePicker
                style={{ width: '100%' }}
                placeholder={['开始时间', '结束时间']}
              />
            </Form.Item>

            <Form.Item
              name="levels"
              label="日志级别"
            >
              <Select
                mode="multiple"
                placeholder="选择要导出的日志级别"
                allowClear
              >
                <Option value="debug">DEBUG</Option>
                <Option value="info">INFO</Option>
                <Option value="warn">WARN</Option>
                <Option value="error">ERROR</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="connections"
              label="连接过滤"
            >
              <Select
                mode="multiple"
                placeholder="选择要导出的连接日志"
                allowClear
              >
                {connections.map(conn => (
                  <Option key={conn.id} value={conn.id}>
                    {conn.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="maxRecords"
              label="最大记录数"
            >
              <InputNumber
                min={1}
                max={100000}
                style={{ width: '100%' }}
                placeholder="留空表示导出所有记录"
              />
            </Form.Item>

            <Form.Item
              name="includeMetadata"
              label="包含元数据"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Form>
        )}
      </Modal>

      {/* 清理配置模态框 */}
      <Modal
        title={
          <Space>
            <SettingOutlined />
            <span>清理配置</span>
          </Space>
        }
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setConfigModalVisible(false)}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={handleUpdateConfig}>
            保存配置
          </Button>,
        ]}
      >
        <Form
          form={configForm}
          layout="vertical"
          initialValues={defaultCleanupConfig}
        >
          <Form.Item
            name="autoCleanup"
            label="自动清理"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="cleanupSchedule"
            label="清理频率"
          >
            <Select>
              <Option value="daily">每日</Option>
              <Option value="weekly">每周</Option>
              <Option value="monthly">每月</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="retentionDays"
            label="默认保留天数"
            rules={[{ required: true, message: '请输入保留天数' }]}
          >
            <InputNumber
              min={1}
              max={365}
              style={{ width: '100%' }}
              addonAfter="天"
            />
          </Form.Item>

          <Form.Item
            name="maxLogSize"
            label="最大日志大小"
            rules={[{ required: true, message: '请输入最大日志大小' }]}
          >
            <InputNumber
              min={100}
              max={10240}
              style={{ width: '100%' }}
              addonAfter="MB"
            />
          </Form.Item>

          <Form.Item
            name="keepErrorLogs"
            label="始终保留错误日志"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>

        <Alert
          message="提示"
          description="自动清理将根据配置定期清理过期日志，建议开启以节省存储空间。"
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      </Modal>
    </div>
  )
}

export default LogManagement